package com.victor.core.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Collections集合工具类
 */
public class CollectionsUtil {

    public static int ASC = 1;//正序
    public static int DESC = -1;//倒序


    /**
     * 按时间进行排序
     */
    public static List<Map<String, Object>> TimeSort(List<Map<String, Object>> list, String field, int sort) {
        Collections.sort(list, new Comparator<Map>() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            /*获取Date*/
            private Date getDate(Map<String, Object> m) {
                if (m == null || m.get(field) == null) {
                    return null;
                }
                try {
                    return sdf.parse(m.get(field).toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            public int compare(Map o1, Map o2) {
                Date d1 = getDate(o1);
                Date d2 = getDate(o2);
                if (d1 == null && d2 == null) {
                    return 0;
                }
                if (d1 == null) {
                    return -1;
                }
                if (d2 == null) {
                    return 1;
                }
                if (sort == 1) {//正序
                    return d1.compareTo(d2);
                } else {//倒序
                    return d2.compareTo(d1);
                }
            }
        });
        return list;
    }


}
